package com.zhou.common.quartz.test.wheel;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 缺点：
 * 1.小顶堆的排序方式，新增和删除元素的时间复杂度都是O(Log2n)
 * <p>
 * 要点：
 * 1.ScheduledExecutorService 的核心执行方法（怎么唤起线程）
 * 2.注意System.nanoTime()(使用场景，在修改系统时间后，还需要希望正常时，可以使用)
 * https://blog.csdn.net/gao_zhennan/article/details/109261319
 *
 * @author xianfeng
 * @date 2023/12/17 15:46
 * @description:
 */
@Slf4j
public class JdkScheduled {


    /**
     * 10000个基本看不出来区别
     */
    @Test
    public void testBigBatch() {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
        for (int i = 0; i < 1000; i++) {
            int delay = RandomUtil.randomInt(300, 25 * 1000);
            String taskName = StrUtil.format("任务{}，{}ms后执行", 15 + i, delay);
            log.info(taskName);
            executor.schedule(() -> {
                log.info("执行了任务，{}", taskName);
            }, delay, TimeUnit.MILLISECONDS);
        }
        ThreadUtil.sleep(1000 * 1000);
    }

    @Test
    public void testNormal() {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(8);
        executor.scheduleWithFixedDelay(() -> {
            log.info("执行了任务，");
        }, 1000, 1000, TimeUnit.MILLISECONDS);
        ThreadUtil.sleep(1000 * 1000);
    }

    @Test
    public void test1() {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
        executor.schedule(() -> {
            log.info("执行了任务1");
        }, 5000, TimeUnit.MILLISECONDS);
        executor.schedule(() -> {
            log.info("执行了任务2");
        }, 5000, TimeUnit.MILLISECONDS);
        executor.schedule(() -> {
            log.info("执行了任务3");
        }, 1000, TimeUnit.MILLISECONDS);
        ThreadUtil.sleep(1000 * 1000);
    }

}
